<template>
  <h1>App component</h1>
  <hr />
  <Table :list="goodsList">
    <!-- 自定义 table 头标题 -->
    <template #thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">商品名称</th>
        <th scope="col">商品价格</th>
        <th scope="col">商品标签</th>
        <th scope="col">操作</th>
      </tr>
    </template>
    <!-- 自定义 行数据 -->
    <template #body="{ row, index }">
      <td>{{ index + 1 }}</td>
      <td>{{ row.goods_name }}</td>
      <td>￥{{ row.goods_price }}</td>
      <td>
        <input
          type="text"
          class="form-control form-control-sm my-ipt"
          v-if="row.inputVisible"
          v-my-focus
          v-model.trim="row.inputValue"
          @blur="clearIpt(row, $event)"
          @keyup.enter="addTag(row)"
          @keyup.esc="console.log('esc')"
        />
        <button
          type="button"
          class="btn btn-primary btn-sm"
          v-else
          @click="row.inputVisible = true"
        >
          +tag
        </button>
        <span
          class="badge badge-info ml-1"
          v-for="(tag, i) in row.tags"
          :key="i"
          >{{ tag }}</span
        >
      </td>
      <td>
        <button
          type="button"
          class="btn btn-danger btn-sm"
          @click="deleteById(row.id)"
        >
          删除
        </button>
      </td>
    </template>
  </Table>
</template>

<script>
import Table from './components/Table.vue'

export default {
  name: 'MyApp',
  components: {
    Table
  },
  data() {
    return {
      goodsList: []
    }
  },
  methods: {
    // 获取商品数据
    async initGetGoodsList() {
      const { data: res } = await this.$http.get('/api/goods')
      console.log(res)
      if (res.status === 0) {
        this.goodsList = res.data
      }
    },
    // 根据 id 删除商品
    deleteById(id) {
      // console.log(id)
      this.goodsList = this.goodsList.filter(item => item.id !== id)
    },
    // 添加标签
    addTag(row) {
      // console.log(row, row.inputValue)
      // 判断空字符 或 已存在
      if (!row.inputValue || row.tags.indexOf(row.inputValue) !== -1)
        return alert('空或已存在')
      row.tags.push(row.inputValue)
      row.inputValue = ''
    },
    clearIpt(row, e) {
      row.inputVisible = false
      row.inputValue = ''
      console.log('clearIpt')
    }
  },
  created() {
    this.initGetGoodsList()
  },
  directives: {
    myFocus: {
      mounted(el) {
        el.focus()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.my-ipt {
  width: 60px;
  display: inline;
}
</style>
